<template>
  <div>
    <!-- 退货管理 -->
    <el-table-form :inline="true" :model="query" class="demo-form">
      <el-form-item class="merge-item">
        <el-select v-model="csmType" style="width: 200px; margin-right: 2px;">
          <el-option label="单据号" value="billCode" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="联系电话" value="csmPhone" />
        </el-select>
        <el-input v-model="csmText" placeholder="请输入内容" clearable />
      </el-form-item>
      <el-form-item label="换货机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
        />
      </el-form-item>
      <el-form-item label="换货原因:" prop="remark">
        <el-input v-model="query.remark" placeholder="请输入内容" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" label="经办日期:">
        <el-date-picker
          v-model="date"
          type="daterange"
          :clearable="false"
          unlink-panels
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="query.billStatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in billStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 查询按钮 -->
      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <!-- 导出按钮 -->
    <!-- <div class="btn-group">
        <div>
          <el-button
            type="primary"
            icon="el-icon-download"
            style="margin-bottom: 20px;"
          >导出</el-button>
        </div>
      </div> -->
    <!-- 表单 -->
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <csm-detail ref="csmDetail" :parent-fetch-data="refresh" :tree-data="treeData" />
    <order-detail ref="orderDetail" :bill-status-map="billStatusMap" />
  </div>
</template>

  <script>
  import {
    barterGasQuery,
    queryMap,
    returnGoodsOrderInvalidNew
  } from '@/api'
  import CsmDetail from '../../components/CsmDetailModal/index.vue'
  import OrderDetail from './components/OrderDetails.vue'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'refundsManage',
    components: {
      CsmDetail,
      OrderDetail
    },
    data() {
      return {
        actionColWidth: 80,
        csmType: 'csmPhone',
        csmText: '',
        date: null,
        query: {
          orgSNNo: '',
          billStatus: '',
          remark: ''
        },
        treeData: [],
        billStatusMap: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'billCode',
            label: '单据号',
            minWidth: 180,
            render: (h, { row }) => {
              return (
                  <el-link underline={false} onClick={() => this.openOrderDetail(row)}>{row.billCode}</el-link>
                )
            }
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 110,
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          },
          {
            prop: 'csmName',
            label: '客户名称',
            width: 110
            // render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmName}</el-link>
          },
          {
            prop: 'csmPhone',
            label: '联系电话',
            width: 110
          },
          {
            prop: 'csmAddress',
            label: '客户地址',
            showOverflowTooltip: true,
            width: 200
          },
          {
            prop: 'remark',
            label: '换货原因',
            width: 200
          },
          {
            prop: 'goodsCount',
            label: '换货数量',
            width: 100
          },
          {
            prop: 'orgName',
            label: '换货机构',
            width: 200
          },
          {
            prop: 'operator',
            label: '换货人'
          },
          {
            prop: 'barterTime',
            width: 150,
            label: '换货时间',
            render: (h, { row }) => (
              <span>
                {row.barterTime && parseTime(row.barterTime, '{y}-{m}-{d} {h}:{i}')}
              </span>
            )
          },
          {
            prop: 'createUser',
            label: '经办人'
          },
          {
            prop: 'createTime',
            width: 150,
            label: '经办时间',
            render: (h, { row }) => (
              <span>
                {row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}')}
              </span>
            )
          },
          {
            prop: 'billStatus',
            label: '状态',
            render: (h, { row }) => (
              <span>
                {row.billStatus &&
                  formatColumnMap(this.billStatusMap, 'value', row.billStatus, 'desc')}
              </span>
            )
          }
        //   {
        //     label: '操作',
        //     fixed: 'right',
        //     className: 'action-col',
        //     width: this.actionColWidth,
        //     render: (h, { row, $index }) => {
        //       return (
        //         <div>
        //           {/* 退货类型为0时不展示审核按钮 */}
        //           {row.billStatus === 1 && row.returnOrderBillType === 0 && (
        //             <el-link
        //               v-permission='3'
        //               underline={false}
        //               size='mini'
        //               onClick={() => this.openReturnOfTheAudit(row, $index)}
        //             >
        //               审核
        //             </el-link>
        //           )}
        //           {row.billStatus !== -1 && row.billStatus !== 2 && (
        //             <el-link
        //               v-permission='2'
        //               underline={false}
        //               size='mini'
        //               type='danger'
        //               onClick={() => this.del(row, $index)}
        //             >
        //               作废
        //             </el-link>
        //           )}
        //         </div>
        //         )
        //     }
        //   }
        ]
      }
    },
    async created() {
      await Promise.all([
        this.getTreeData(),
        this.queryOptionsMap()
      ])
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.csmType] = this.csmText || undefined
        if (this.date && this.date.length > 0) {
          query.startDt = moment(this.date[0]).format()
          query.endDt = moment(this.date[1]).format()
        //   const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        //   if (diff > 366) {
        //     this.$message.error('退货日期最大支持查询1年')
        //     return
        //   }
        }
        const res = await barterGasQuery(query)
        this.tableData.data = res.data.rows || []
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'BarterBillStatus' })
        //   mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          // mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
        //   mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
        //   mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
        //   mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
        //   mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
        //   mergeAsyncFunc(queryMap, { enumName: 'OrderSource' }),
        //   mergeAsyncFunc(queryMap, { enumName: 'CalcType' })
        ])
        this.billStatusMap = res1.data
      },
      // 订单号
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row)
      },
      // 审核
      async openReturnOfTheAudit(row) {
        await this.$refs.returnOfTheAudit.open(row, 'audit')
        this.$refs.lbTable.fetch()
      },
      // 作废
      del(row, index) {
        this.$confirm('确认要作废该退货单吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在作废',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          returnGoodsOrderInvalidNew({ billCode: row.billCode, billType: row.billType })
            .then(() => {
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.$refs.lbTable.fetch({ currentPage: 1 })
              this.$refs['returnOfTheAudit'].reset()
            })
            .finally(() => {
              loading.close()
            })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      }
    //   // 点击订单号
    //   async openOrderDetail(row) {
    //     await this.$refs.orderDetail.open(row, true)
    //   }
    }
  }
  </script>

  <style lang="scss" scoped>
  .btn-group {
    display: flex;
    justify-content: space-between;
  }
  </style>
